home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / answrbok / 6_6.lha / 6_6 / 6_6sub_eq.c < prev    next >
C/C++ Source or Header  |  1993-08-08  |  1KB  |  62 lines

  1. * Copyright (c) 1990 by AT&T Bell Telephone Laboratories, Incorporated. */
  2. * The C++ Answer Book */
  3. * Tony Hansen */
  4. * All rights reserved. */
  5. / substring = "abc"
  6. ifdef NOTDEF            // DELETE
  7. include <str.h>
  8. else                // DELETE
  9. include "6_6.h"        // DELETE
  10. endif                // DELETE
  11. ubstring &substring::operator=(char *cp)
  12.  
  13.    // disconnect current shared string
  14.    if (str->p->refcnt > 1)
  15. {
  16. str->p->refcnt--;
  17. srep *oldp = str->p;
  18. int oldoffset = s - oldp->s;
  19. str->p = new srep(oldp->s, oldp->size);
  20. s = str->p->s + oldoffset;
  21. }
  22.  
  23.    const int stlen = strlen(cp);
  24.  
  25.    // same size, simply copy data
  26.    if (len == stlen)
  27. {
  28. if (len > 0)
  29.     memcpy(s, cp, len);
  30. }
  31.  
  32.    // expand or shrink data area
  33.    else
  34. {
  35. // allocate the new data segment
  36. char *sps = str->p->s;
  37. const int s1len = s - sps;
  38. const int s3len = strlen(sps) - len - s1len;
  39. char *newdata =
  40.     new char[s1len + stlen + s3len + 1];
  41.  
  42. // copy in the data
  43. if (s1len > 0)
  44.     memcpy(newdata, sps, s1len);
  45. if (stlen > 0)
  46.     memcpy(newdata+s1len, cp, stlen);
  47. if (s3len > 0)
  48.     memcpy(newdata + s1len + stlen,
  49.     s + len, s3len);
  50. newdata[s1len + stlen + s3len] = '\0';
  51.  
  52. // replace pointers
  53. delete str->p->s;
  54. str->p->s = newdata;
  55. str->p->size = s1len + stlen + s3len + 1;
  56. s = newdata + s1len;
  57. len = stlen;
  58. }
  59.  
  60.    return *this;
  61.  
  62.